package com.project.easy.common.framework.core.boot;


import  com.project.easy.common.util.exception.file.FileNotExistException;
import  com.project.easy.common.util.exception.print.PrintException;
import  com.project.easy.common.util.string.StringUtil;
import org.springframework.boot.Banner;
import org.springframework.boot.ansi.AnsiOutput;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.SpringVersion;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.File;
import java.io.InputStream;
import java.util.Objects;

/**
 * @author GreatorMan.cool
 * @copyright: Copyright (c) 2020
 * @company: 扬起科技有限公司
 * @date 2021/9/6 22:29
 * @description: boot 时间格式
 */
public abstract class YqkjApplication {
    /**
     * 配置文件
     */
    private final static  String CONFIG_FILE1 = "classpath:META-INF\\app.properties";
    /**
     * 参数配置
     */
    private final static   String CONFIG_NAME = "appConfigName";

    /**
     * 程序启动入口
     * @param classs 主分class
     * @param args 参数
     */
    public static ApplicationContext run(Class classs, String[] args) {
        if (Objects.isNull(classs)) {
            classs = YqkjApplication.class;
        }
        String config = CONFIG_FILE1;
        if (System.getProperties().containsKey(CONFIG_NAME)) {
            config = System.getProperties().getProperty(CONFIG_NAME);
        }
        // System 中的属性只支持绝对路径
        if (StringUtil.isNotBlank(config) && !CONFIG_FILE1.equals(config)) {
            File file = new File(config);
            if (!file.exists()) {
                throw new FileNotExistException(String.format("配置%s文件不存在,配置文件只支持绝对路径", config));
            }
            if (!file.canRead()) {
                throw new FileNotExistException(String.format("配置%s文件不能读", config));
            }
        }

        AnsiOutput.setEnabled(AnsiOutput.Enabled.DETECT);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource resource = resolver.getResource("classpath:META-INF\\app.properties");
        if (resource.exists()) {
            try {
                InputStream inputStream = resource.getInputStream();
                System.getProperties().load(inputStream);
            } catch (Exception e) {
                PrintException.print(e);
            }
        }
        ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder(classs)//
                .main(SpringVersion.class) // 这个是为了可以加载 Spring 版本
                .bannerMode(Banner.Mode.CONSOLE)// 控制台打印
                .run(args);

        return  applicationContext;
    }
}
